package com.ebt.m.customer.service;

import android.app.IntentService;
import android.content.Context;
import android.content.Intent;
import android.os.IBinder;

import com.ebt.m.AppInitService;
import com.ebt.m.commons.utils.NetUtils;
import com.ebt.m.customer.constant.CustomerConstant;
import com.ebt.m.customer.db.CustomerDBManager;
import com.ebt.m.customer.net.json.CustomerListJson;
import com.ebt.m.data.rxModel.api.EBTAPI;

import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;

/**
 * 后台下载客户列表（所有客户），并将数据存储到customer_simple表中
 */
public class FetchNetCustomerService extends IntentService {

    public static void startThis(Context context) {
        Intent intent = new Intent(context, FetchNetCustomerService.class);
        context.startService(intent);
    }

    public FetchNetCustomerService() {
        super("FetchNetCustomerService");
    }

    @Override
    protected void onHandleIntent(Intent intent) {
        if (NetUtils.isNetworkAvailable(this)) {
            EBTAPI ebtapi = AppInitService.getEbtApi();
            ebtapi.getCustomerList().subscribe(getCustomerListSubscriber());
        }
    }

    private Observer<CustomerListJson> getCustomerListSubscriber() {
        return new Observer<CustomerListJson>() {
            @Override
            public void onSubscribe(Disposable d) {
            }

            @Override
            public void onNext(CustomerListJson customerListJson) {
                if (customerListJson != null && customerListJson.data != null) {
                    storeCustomerList(customerListJson);
                }
            }

            @Override
            public void onError(Throwable e) {
                e.printStackTrace();
            }

            @Override
            public void onComplete() {
            }
        };
    }

    private void storeCustomerList(CustomerListJson customerListJson) {
        if (customerListJson == null) {
            return;
        }

        CustomerDBManager
                .getInstance()
                .clearTable(getApplicationContext(), CustomerConstant.CustomerSimple.TABLE_NAME);

        CustomerDBManager
                .getInstance()
                .saveSimpleCustomers(getApplicationContext(), customerListJson.data);
    }

    @Override
    public void onCreate() {
        super.onCreate();
    }

    @Override
    public void onStart(Intent intent, int startId) {
        super.onStart(intent, startId);
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        return super.onStartCommand(intent, flags, startId);

    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }

    @Override
    public IBinder onBind(Intent intent) {
        return super.onBind(intent);
    }
}